<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\Exception;
use think\exception\ValidateException;

use app\common\model\User;
use app\common\model\Feedback;
use app\common\model\UserResume as Resume;
use app\common\model\ResumeWork;
use app\common\model\ResumeEducation;
use app\common\model\ApplyInduction;
use app\common\model\CheckApprove;
use app\common\model\CheckRule;
use app\common\model\UserSection;
use app\common\model\UserSectionLevel;
use app\common\model\SystemMenu;
use app\common\model\UserCompany;
use app\common\model\SendSms;
use app\common\model\ResumeJob;
use app\common\model\ResumeRound;

use app\common\validate\ResumeValidate;
use app\common\validate\ResumeWorkValidate;
use app\common\validate\ResumeEducationValidate;
use app\Request;
use service\JsonService as Json;
use service\SendSms as SendSmsService;

class UserController extends BaseController
{
    /**
     * 用户信息
     */
    public function getUserInfo()
    {
        $field = 'name, staff_no, avatars, check_clock_id, company_id, section_id, section_level_id';
        $info = User::getFind(['id' => $this->user_id], $field);
        if(!$info) return Json::fail('暂无数据');

        if($info['check_clock_id'] != 0){
            $checkRuleInfo = CheckRule::getFind(['id' => $info['check_clock_id']]);

            if($checkRuleInfo === false){
                $clockRule = [];
            }else{
                $clockRule['name']       = $checkRuleInfo['name'];
                $clockRule['start_time'] = secondToHour($checkRuleInfo['start_time']);
                $clockRule['end_time']   = secondToHour($checkRuleInfo['end_time']);
            }
        }else{
            $clockRule = [];
        }

        $info['is_data'] = 0;
        $levelInfo = UserSectionLevel::getFind(['id' => $info['section_level_id']]);
        if($levelInfo && $levelInfo['level'] == 1) $info['is_data'] = 1;

        if($info['section_id']){
            $info['section_name'] = UserSection::getVal(['id' => $info['section_id']], 'name');
            if($info['section_level_id']) $info['section_name'] .= '(' . $levelInfo['name'] . ')';
        }else{
            $info['section_name'] = '';
        }

        if($info['company_id']){
            $info['company_name'] = UserCompany::getVal(['id' => $info['company_id']], 'name');
        }else{
            $info['company_name'] = '';
        }

        $info['clock_rule'] = $clockRule;
        $info['staff_no']   = $info['staff_no'];
        unset($info['check_clock_id']);

        return Json::success('ok', $info);
    }

    /**
     * 入职申请
     */
    public function setInduction()
    {
        $param['name']             = Request()->param('name', '');
        $param['mobile']           = Request()->param('mobile', '');
        $param['section_id']       = Request()->param('section_id', 0);
        $param['section_level_id'] = Request()->param('section_level_id', 0);
        $param['card_num']         = Request()->param('card_num', '');
        $param['mobile']           = Request()->param('mobile', '');
        $param['job_time']         = Request()->param('job_time', 0);
        $code                      = Request()->param('code', '');
        $param['user_id']          = $this->user_id;

        if($param['section_id'] == 0) return Json::fail('部门不能为空');
        if($param['section_level_id'] == 0) return Json::fail('部门级别不能为空');
        if(empty($param['card_num'])) return Json::fail('银行卡号不能为空');

        $sectionInfo = UserSection::getFind(['id' => $param['section_id']]);

        $sectionInfo = UserSection::getFind(['id' => $param['section_id']]);
        if($param['section_id'] != 2
        && $sectionInfo['cate_id'] == 2
        && User::getNum(['section_id' => $param['section_id']]) >= $sectionInfo['people_num']){
            return Json::fail('申请失败：部门人数达到上限');
        }

        // $codeFlag = SendSms::check($param['mobile'], $code);
        // if($codeFlag !== true) return Json::fail($codeFlag);

        $info = ApplyInduction::getFind(['user_id' => $this->user_id]);

        if($info !== false && $info['status'] != 3) return Json::fail('请勿重复提交申请');

        $param['job_time'] = strtotime($param['job_time']);
        
        if($info !== false && $info['status'] == 3){
            $flag = ApplyInduction::edit([
                'id'                => $info['id'], 
                'status'            => 1, 
                'name'              => $param['name'], 
                'mobile'            => $param['mobile'],
                'section_id'        => $param['section_id'],
                'section_level_id'  => $param['section_level_id'],
                'card_num'          => $param['card_num'],
                'job_time'          => $param['job_time'],
                'create_time'       => time()
            ]);
        }else{
            $param['back_msg']    = '';
            $param['finish_time'] = '';
            
            $flag = ApplyInduction::add($param);
        }

        if($flag === false) return Json::fail('申请失败');

        /** 红点提示 */
        SystemMenu::setRed([0], $this->user_id, 10, 3, $flag['id']);

        if(UserSection::getVal(['id' => $param['section_id'], 'is_out' => 1], 'id')){
            $isJump = 1;
        }else{
            if(UserSection::getVal(['id' => $param['section_id'], 'cate_id' => 2], 'id') 
            && UserSectionLevel::getVal(['id' => $param['section_level_id'], 'level' => 1], 'id')
            && $param['section_id'] != 2
            ){
                $isJump = 1;
            }else{
                $isJump = 0;
            }
        }

        return Json::success('提交申请成功', ['is_jump' => $isJump]);
    }

    /**
     * 入职申请详情
     */
    public function getInductionShow()
    {
        $info = ApplyInduction::getFind(['user_id' => $this->user_id]);

        if($info === false) return Json::fail('还未提交申请');

        if($info['section_id']){
            $info['section_name'] = UserSection::getVal(['id' => $info['section_id']], 'name');
            if($info['section_level_id']) $info['section_name'] .= '(' . UserSectionLevel::getVal(['id' => $info['section_level_id']], 'name') . ')';
        }else{
            $info['section_name'] = '';
        }

        if($info['company_id']){
            $info['company_name'] = UserCompany::getVal(['id' => $info['company_id']], 'name');
        }else{
            $info['company_name'] = '';
        }

        unset($info['user_id']);
        return Json::success('ok', $info);
    }

    /**
     * 获取部门列表
     */
    public function getSectionTree()
    {
        return Json::success('ok', UserSection::sectionTree());
    }




    /**
     * 我的简历
     */
    public function getResumeShow()
    {
        $info = Resume::getResumeShow($this->user_id);
        if($info === false) return Json::fail('暂无数据~');

        $info['company_name'] = UserCompany::getVal(['id' => $info['company_id']], 'name');

        return Json::success('ok', $info);
    }

    /**
     * 编辑简历
     */
    public function setResume()
    {
        $resumeId     = Request()->param('resume_id', 0);
        $companyId    = Request()->param('company_id', 0);
        $name         = Request()->param('name', '');
        $sex          = Request()->param('sex', 0);
        $birthday     = Request()->param('birthday', 0);
        $education    = Request()->param('education', 0);
        $mobile       = Request()->param('mobile', '');
        $cardNum      = Request()->param('card_num', '');
        $address      = Request()->param('address', '');
        $code         = Request()->param('code', '');
        $selfEvaluate = Request()->param('self_evaluate', '');
        $faceTime     = Request()->param('face_time', '');

        // if(isset($param['code'])){
        //     $codeFlag = SendSms::check($param['mobile'], $param['code']);
        //     if($codeFlag !== true) return Json::fail($codeFlag);
        // }

        if(!empty($faceTime)){
            list($days, $times1, $times2) = explode('/', $faceTime);
            $faceTime1 = $days . ' ' . $times1;
            $faceTime2 = $days . ' ' . $times2;
        }else{
            $faceTime1 = 0;
            $faceTime2 = 0;
        }

        if(!empty($birthday)) {
            $birthday = strtotime($birthday);
            $age      = getAge($birthday);
        }

        if($faceTime){
            $resumeJobData = [
                'user_id'         => $this->user_id,
                'resume_id'       => $resumeId,
                'company_id'      => $companyId,
                'face_start_time' => $faceTime1,
                'face_end_time'   => $faceTime2,
            ];
    
            $resumeJobFlag = ResumeJob::add($resumeJobData);
            if($resumeJobFlag === false) return Json::fail();
        }

        $resumeData = [
            'id'            => $resumeId,
            'company_id'    => $companyId,
            'name'          => $name,
            'sex'           => $sex,
            'birthday'      => $birthday,
            'age'           => $age,
            'education'     => $education,
            'mobile'        => $mobile,
            'card_num'      => $cardNum,
            'address'       => $address,
            'self_evaluate' => $selfEvaluate,
        ];

        $flag = Resume::edit($resumeData);
        if($flag === false) return Json::fail();
        return Json::success();
    }

    /**
     * 新增教育经历
     */
    public function setEducation()
    {
        $param = input('');
    
        try{
            validate(ResumeEducationValidate::class)->scene('add')->check($param);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $param['user_id']    = $this->user_id;
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time']   = strtotime($param['end_time']);

        $flag = ResumeEducation::add($param);
        if($flag === false) return Json::fail('添加失败');
        return Json::success('添加成功');
    }

    /**
     * 删除教育经历
     */
    public function delEducation()
    {
        $id = Request()->param('education_id', 0);

        $flag = ResumeEducation::destroy($id);
        if(!$flag) return Json::fail('删除失败');
        return Json::success('删除成功');
    }

    /**
     * 新增工作经历
     */
    public function setWork()
    {
        $param = input('');
    
        try{
            validate(ResumeWorkValidate::class)->scene('add')->check($param);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $param['user_id']    = $this->user_id;
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time']   = strtotime($param['end_time']);

        $flag = ResumeWork::add($param);
        if($flag === false) return Json::fail('添加失败');
        return Json::success('添加成功');
    }

    /**
     * 删除工作经历
     */
    public function delWork()
    {
        $id = Request()->param('work_id', 0);

        $flag = ResumeWork::destroy($id);
        if(!$flag) return Json::fail('删除失败');
        return Json::success('删除成功');
    }

    /** 
     * 意见反馈
     */
    public function setFeedback()
    {
        $addArr = [
            'user_id' => $this->user_id,
            'content' => Request()->param('content', ''),
        ];

        $flag = Feedback::add($addArr);
        if($flag === false) return Json::fail('反馈失败');
        return Json::success('反馈成功');
    }

    /**
     * 查询是否审批人|抄送人
     */
    public function isApprove()
    {
        $isBe = 0;
        $userInfo = User::getFind(['id' => $this->user_id]);
        if(!$userInfo) return Json::success('ok', ['is_be' => $isBe]);

        $approveInfo = CheckApprove::getFind(['section_id' => $userInfo['section_id']]);
        if(!$userInfo) return Json::success('ok', ['is_be' => $isBe]);

        if($approveInfo['approve_id'] == $this->user_id) $isBe = 1;
        if($approveInfo['send_id'] == $this->user_id) $isBe = 2;

        return Json::success('ok', ['is_be' => $isBe]);
    }

    /**
     * 发送短信验证码
     */
    public function sendSms()
    {
        $mobile = Request()->param('mobile', '');

        $smsModel = new SendSmsService();
        $code = rand(100000, 999999);

        $sms = $smsModel->send_verify($mobile, $code);

        if($sms !== true) return Json::fail($sms);

        $param = [
            'mobile'          => $mobile,
            'code'            => $code,
            'expiration_time' => 60 * 5
        ];

        $flag = SendSms::add($param);
        if(!$flag) return Json::fail();
        return Json::success();
    }

    /**
     * 公司列表
     */
    public function getCompanyList()
    {
        return Json::success('ok', UserCompany::getList([], 0, 0, 0, 'id, name'));
    }



    /**
     * 我的团队
     */
    public function getMyTeam()
    {
        $where[] = ['is_staff', '=', 1];
        $where[] = ['status', '=', 1];
        $where[] = ['section_id', '=', User::getVal(['id' => $this->user_id], 'section_id')];

        return Json::success('ok', User::getList($where, 0, 0, 0, 'id, name, avatars'));
    }

    /**
     * 供应商每日交付数据
     */
    public function getDeliverData()
    {
        $userId = Request()->param('user_id', 0);
        $sort   = Request()->param('sort', 0);

        $userInfo = User::getFind(['id' => $this->user_id]);
        $ids = User::getCol(['section_id' => $userInfo['section_id'], 'status' => 1], 'id');

        if($userId){
            $where[] = ['user_id', '=', $userId];
        }else{
            $ids = User::getCol(['section_id' => User::getVal(['id' => $this->user_id], 'section_id'), 'status' => 1], 'id');
            $where[] = ['user_id', 'in', $ids];
        }

        $model = ResumeRound::where($where);

        switch ($sort) {
            case 1:
                $claim  = $model->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereDay('claim_time|create_time')->count();
                $invite = $model->where([['status', 'in', [2, 3, 4, 5]]])->whereDay('invite_time')->count();
                $pass   = $model->where([['status', 'in', [4, 5]]])->whereDay('pass_time')->count();
                $join   = $model->where([['status', '=', 5]])->whereDay('join_time')->count();
                break;
            case 2:
                $claim  = $model->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereWeek('claim_time|create_time')->count();
                $invite = $model->where([['status', 'in', [2, 3, 4, 5]]])->whereWeek('invite_time')->count();
                $pass   = $model->where([['status', 'in', [4, 5]]])->whereWeek('pass_time')->count();
                $join   = $model->where([['status', '=', 5]])->whereWeek('join_time')->count();
                break;
            case 3:
                $claim  = $model->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereMonth('claim_time|create_time')->count();
                $invite = $model->where([['status', 'in', [2, 3, 4, 5]]])->whereMonth('invite_time')->count();
                $pass   = $model->where([['status', 'in', [4, 5]]])->whereMonth('pass_time')->count();
                $join   = $model->where([['status', '=', 5]])->whereMonth('join_time')->count();
                break;
            case 4:
                $claim  = $model->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereYear('claim_time|create_time')->count();
                $invite = $model->where([['status', 'in', [2, 3, 4, 5]]])->whereYear('invite_time')->count();
                $pass   = $model->where([['status', 'in', [4, 5]]])->whereYear('pass_time')->count();
                $join   = $model->where([['status', '=', 5]])->whereYear('join_time')->count();
                break;
            default:
                $claim  = $model->where([['status', 'in', [1, 2, 3, 4, 5]]])->count();
                $invite = $model->where([['status', 'in', [2, 3, 4, 5]]])->count();
                $pass   = $model->where([['status', 'in', [4, 5]]])->count();
                $join   = $model->where([['status', '=', 5]])->count();
                break;
        }

        $data = [
            'claim'  => $claim,
            'invite' => $invite,
            'pass'   => $pass,
            'join'   => $join,
        ];

        return Json::success('ok', $data);
    }
}